﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MethodWorx.CMS.Workflow;
using MethodWorx.CMS.Providers;
using MethodWorx.CMS.Membership;

namespace MethodWorx.CMS.TemplateParser.Installer
{
    public class InstallerWorkflowExecutionContext : IWorkflowExecutionContext
    {
        public InstallerWorkflowExecutionContext(ICmsDataProvider provider, InstallerParser parser, User user)
        {
            this.CmsDataProvider = provider;
            this.CurrentUser = user;

            foreach (var step in parser.WizardSteps)
            {
                foreach (var prompt in step.Prompts)
                {
                    values.Add(prompt.Variable, prompt.Value);
                }
            }
        }

        private Dictionary<string, object> values = new Dictionary<string, object>();
        private Dictionary<string, List<string>> errors = new Dictionary<string, List<string>>();

        public ICmsDataProvider CmsDataProvider { get; set; }
        public User CurrentUser { get; private set; }

        public object GetWorkflowValue(string name)
        {
            return this.values[name];
        }

        public IEnumerable<string> GetWorkflowErrors(string name)
        {
            if(errors.ContainsKey(name))
                return errors[name].AsReadOnly();
            else
                return new string[0];
        }

        public void AddWorkflowError(string name, string value)
        {
            if(!errors.ContainsKey(name))
                errors.Add(name, new List<string>());

            errors[name].Add(value);
        }

        public bool IsValid()
        {
            return (this.errors.Count == 0);
        }

        public Dictionary<string, string> GetAllWorkflowValues()
        {
            Dictionary<string, string> dict = new Dictionary<string, string>();
            foreach(var value in this.values.Keys)
            {

                dict.Add(value, this.values[value].ToString());
            }

            return dict;
        }


        public void AddWorkflowValue(string name, object value)
        {
            this.values.Add(name, value);
        }


        public T GetService<T>()
        {
            return this.CmsDataProvider.GetService<T>();
        }
    }
}
